package cn.shyouchi.wuguanjia.android.ui.profile;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jeanboy.cropview.cropper.CropperHandler;
import com.jeanboy.cropview.cropper.CropperManager;
import com.jeanboy.cropview.cropper.CropperParams;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.Global;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.UserStorageProvider;
import cn.shyouchi.wuguanjia.android.api.profile.ProfileApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.event.LogoutEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.model.UserData;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.home.security.thread.me.FilloutProfileActivity;
import cn.shyouchi.wuguanjia.android.ui.home.security.thread.me.ProfileUpdateActivity;
import cn.shyouchi.wuguanjia.android.ui.login.LoginActivity;
import cn.shyouchi.wuguanjia.android.widget.GlideCircleTransform;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.ConfirmIdInfoDialogFragment;
import io.realm.Realm;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static cn.shyouchi.wuguanjia.android.ui.home.security.thread.me.ProfileUpdateActivity.UPDATE_PROFILE_FIELD_BAND;
import static cn.shyouchi.wuguanjia.android.ui.home.security.thread.me.ProfileUpdateActivity.UPDATE_PROFILE_FIELD_SECURITY;

@RuntimePermissions
public class ProfileActivity extends BaseActivity implements CropperHandler, ConfirmIdInfoDialogFragment.ConfirmIdInfoDialogListener {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.btn_exit)
    Button mBtnExit;
    @BindView(R.id.img_header)
    ImageView mImgHeader;
    @BindView(R.id.item_header)
    RelativeLayout mItemHeader;
    @BindView(R.id.item_qrcode)
    RelativeLayout mItemQrcode;
    @BindView(R.id.item_idcard)
    RelativeLayout mItemIdcard;
    @BindView(R.id.item_person_info)
    RelativeLayout mItemPersonInfo;
    @BindView(R.id.tv_bank_num)
    TextView mTvBankNum;
    @BindView(R.id.item_bank_num)
    RelativeLayout mItemBankNum;
    @BindView(R.id.tv_security_num)
    TextView mTvSecurityNum;
    @BindView(R.id.item_security_num)
    RelativeLayout mItemSecurityNum;

    UserStorage mUserStorage;


    @Override
    public int initContentView() {
        return R.layout.activity_profile;
    }

    @Override
    public void initInjector() {
        mUserStorage = UserStorageProvider.Default();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        CropperManager.getInstance().build(this);
        fillDetail();
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.item_header, R.id.item_qrcode, R.id.item_idcard, R.id.item_person_info, R.id.item_bank_num, R.id.item_security_num, R.id.btn_exit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.item_header:
                showSelHeaderDialog();
                break;
            case R.id.item_qrcode:
                startActivity(new Intent(mContext, PersonQRCodeActivity.class));
                break;
            case R.id.item_idcard:
                showNoticeDialog(UserStorageProvider.Default().getUserData());
                break;
            case R.id.item_person_info:
                startActivity(new Intent(mContext, ProfileUpdateActivity.class));
                break;
            case R.id.item_bank_num:
                upBandNum();
                break;
            case R.id.item_security_num:
                upSecurityNum();
                break;
            case R.id.btn_exit:
                showAlert("确定退出当前用户？");
                break;
        }
    }

    private void showAlert(String msg) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext, android.app.AlertDialog.THEME_HOLO_LIGHT);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                startActivity(new Intent(mContext, LoginActivity.class));
                EventBus.getDefault().post(new LogoutEvent());
                finish();
            }
        });
        builder.create().show();
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromCamera() {
        CropperManager.getInstance().pickFromCamera();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromGallery() {
        CropperManager.getInstance().pickFromGallery();
    }


    private void fillDetail() {

        loadHead(Global.BASE_URL + mUserStorage.getUserData().getAvatar());

        mTvBankNum.setText(mUserStorage.getUserData().getBank_card());
        mTvSecurityNum.setText(mUserStorage.getUserData().getSecurity_card());
    }


    private void loadHead(String path) {
        Glide.with(mContext)
                .load(path)
                .placeholder(R.mipmap.ic_default_header)
                .transform(new GlideCircleTransform(mContext))
                .into(mImgHeader);
    }

    public void upBandNum() {
        FilloutProfileActivity.start(this, "银行卡号", String.valueOf(mUserStorage.getUserData().getBank_card()), UPDATE_PROFILE_FIELD_BAND, true, InputType.TYPE_CLASS_NUMBER);

    }

    public void upSecurityNum() {
        FilloutProfileActivity.start(this, "保安证号", String.valueOf(mUserStorage.getUserData().getSecurity_card()), UPDATE_PROFILE_FIELD_SECURITY, true, InputType.TYPE_CLASS_NUMBER);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        CropperManager.getInstance().handlerResult(requestCode, resultCode, data);

        if (requestCode == 1001 && resultCode == 1000) {
            fillDetail();
        }

    }


    private synchronized void showSelHeaderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("设置头像");
        builder.setCustomTitle(tvTitle);
        builder.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        ProfileActivityPermissionsDispatcher.pickFromCameraWithCheck(ProfileActivity.this);
                        break;
                    case 1:
                        ProfileActivityPermissionsDispatcher.pickFromGalleryWithCheck(ProfileActivity.this);
                        break;
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public CropperParams getParams() {
        return new CropperParams(856, 856);
    }

    @Override
    public void onCropped(Uri uri) {
        uploadHeader(uri.getPath());
    }

    @Override
    public void onCropCancel() {

    }

    @Override
    public void onCropFailed(String msg) {

    }


    private void uploadHeader(String path) {
        new ProfileApi(mContext)
                .upHeader(path)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult result) {
                        final String s = result.getResultMessage().toString();
                        Realm.getDefaultInstance()
                                .executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        UserStorageProvider.Default().getUserData().setAvatar(s);
                                        fillDetail();
                                    }
                                });
                    }
                });
    }


    public void showNoticeDialog(UserData user) {
        ConfirmIdInfoDialogFragment dialog = new ConfirmIdInfoDialogFragment();
        dialog.show(getFragmentManager().beginTransaction(), "NoticeDialogFragment", user);
    }


    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {

    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {

    }
}
